<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\CreateRoomRequest;
use App\Services\RoomService;
use App\Traits\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RoomController extends Controller
{
    use ApiResponse;

    protected $roomService;

    public function __construct(RoomService $roomService)
    {
        $this->roomService = $roomService;
    }

    /**
     * 创建房间
     */
    public function store(CreateRoomRequest $request): JsonResponse
    {
        try {
            $user = Auth::user();
            $room = $this->roomService->createRoom($request->validated(), $user->id);

            return $this->created([
                'room' => $room
            ], '房间创建成功');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 加入房间
     */
    public function join(Request $request, string $roomId): JsonResponse
    {
        $request->validate([
            'roomId' => 'required|string',
        ]);

        try {
            $user = Auth::user();
            $room = $this->roomService->joinRoom($roomId, $user->id);

            return $this->success([
                'room' => $room
            ], '加入房间成功');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 获取房间信息
     */
    public function show(string $roomId): JsonResponse
    {
        try {
            $user = Auth::user();
            $room = $this->roomService->getRoomInfo($roomId, $user->id);

            return $this->success([
                'room' => $room
            ], '获取房间信息成功');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 获取房间菜单
     */
    public function getMenu(string $roomId): JsonResponse
    {
        try {
            $user = Auth::user();
            $room = $this->roomService->getRoomInfo($roomId, $user->id);

            if (!$room->menu) {
                return $this->success([
                    'menu' => null,
                    'categories' => [],
                    'dishes' => [],
                    'message' => '房间暂无菜单'
                ], '房间暂无菜单');
            }

            $menu = $room->menu;
            $dishes = $this->roomService->getMenuDishes($menu);
            $categories = $this->roomService->getCategories();

            return $this->success([
                'menu' => [
                    'id' => $menu->id,
                    'name' => $menu->name,
                    'description' => $menu->description,
                    'source_type' => $menu->source_type,
                    'is_public' => $menu->is_public,
                    'created_at' => $menu->created_at,
                ],
                'categories' => $categories,
                'dishes' => $dishes->map(function ($dish) {
                    return [
                        'id' => $dish->id,
                        'name' => $dish->name,
                        'description' => $dish->description,
                        'image' => $dish->image,
                        'category' => $dish->category ? $dish->category->name : null,
                        'category_id' => $dish->category_id,
                        'tags' => $dish->tags,
                        'flavors' => $dish->flavors,
                        'cooking_time' => $dish->cooking_time,
                        'is_featured' => $dish->is_featured,
                        'dish_source' => $dish->dish_source,
                        'creator' => $dish->creator ? $dish->creator->nickname : null,
                        'source_dish_id' => $dish->source_dish_id,
                    ];
                })
            ], '获取房间菜单成功');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 更新房间设置
     */
    public function updateSettings(Request $request, string $roomId): JsonResponse
    {
        $request->validate([
            'settings' => 'required|array',
            'settings.allowParticipantAdd' => 'sometimes|boolean',
            'settings.allowParticipantSuggest' => 'sometimes|boolean',
            'settings.showUserFavorites' => 'sometimes|boolean',
        ]);

        try {
            $user = Auth::user();
            $this->roomService->updateRoomSettings($roomId, $request->input('settings'), $user->id);

            return $this->success([], '房间设置更新成功');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 关闭房间
     */
    public function destroy(string $roomId): JsonResponse
    {
        try {
            $user = Auth::user();
            $this->roomService->closeRoom($roomId, $user->id);

            return $this->success([], '房间已关闭');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 获取用户房间列表
     */
    public function myRooms(Request $request): JsonResponse
    {
        try {
            $user = Auth::user();
            $filters = $request->only(['type', 'status', 'limit', 'offset']);
            
            $result = $this->roomService->getUserRooms($user->id, $filters);

            return $this->success($result, '获取用户房间列表成功');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 获取最近房间
     */
    public function recentRooms(Request $request): JsonResponse
    {
        try {
            $user = Auth::user();
            $limit = $request->input('limit', 10);
            $days = $request->input('days', 7);
            
            $result = $this->roomService->getRecentRooms($user->id, $limit, $days);

            return $this->success($result, '获取最近房间成功');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 获取置顶房间
     */
    public function pinnedRooms(): JsonResponse
    {
        try {
            $user = Auth::user();
            $result = $this->roomService->getPinnedRooms($user->id);

            return $this->success($result, '获取置顶房间成功');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 设置房间置顶
     */
    public function pinRoom(string $roomId): JsonResponse
    {
        try {
            $user = Auth::user();
            $success = $this->roomService->pinRoom($user->id, $roomId);

            if (!$success) {
                return $this->error('房间不存在或无权限操作', 404);
            }

            return $this->success([], '房间已置顶');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 取消房间置顶
     */
    public function unpinRoom(string $roomId): JsonResponse
    {
        try {
            $user = Auth::user();
            $success = $this->roomService->unpinRoom($user->id, $roomId);

            if (!$success) {
                return $this->error('房间不存在或无权限操作', 404);
            }

            return $this->success([], '房间已取消置顶');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }
}